package study.week05.gateway.outbound;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpUtil;
import org.springframework.beans.factory.annotation.Autowired;
import study.week05.gateway.filter.CustomHttpFilter;
import study.week05.gateway.router.CustomRouter;
import study.week05.uti.HttpClientUtil;

import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.concurrent.ExecutorService;

import static io.netty.handler.codec.http.HttpHeaderNames.CONNECTION;
import static io.netty.handler.codec.http.HttpHeaderValues.KEEP_ALIVE;
import static io.netty.handler.codec.http.HttpResponseStatus.NO_CONTENT;
import static io.netty.handler.codec.http.HttpResponseStatus.OK;
import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;

public class ResponseHandler {


    /**
     *
     * @param fullRequest
     * @param ctx
     */
    public FullHttpResponse generateResponse(FullHttpRequest fullRequest, ChannelHandlerContext ctx ,String server) {
        String uri = fullRequest.uri();
        String target = server+uri;
        String body = "business server error.";
        try {
            String bodyTemp = HttpClientUtil.httpGet(target);
            if(bodyTemp!=null ){
                body = bodyTemp;
            }
        }catch (Exception ex){
            ex.printStackTrace();
        }
        FullHttpResponse response = null;
        try {

            response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(body.getBytes(StandardCharsets.UTF_8)));
            response.headers().set("Content-Type", "application/json");
            response.headers().setInt("Content-Length", response.content().readableBytes());


        } catch (Exception e) {
            System.out.println("处理出错:"+e.getMessage());
            response = new DefaultFullHttpResponse(HTTP_1_1, NO_CONTENT);
        }
        return response;
    }


}
